package com.coocaa.x.app.hall.view.widget;

import android.content.Context;
import android.os.IBinder;
import android.os.RemoteException;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.Cache;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.PMUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppUpdateBean;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Update_Apps;
import com.coocaa.x.service.litedownloader2.ErrorCode;
import com.coocaa.x.service.litedownloader2.aidl.DownloadTask;
import com.coocaa.x.service.litedownloader2.aidl.ILiteDownloadServiceListener;
import com.coocaa.x.service.litedownloader2.aidl.ILiteDownloaderService;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppDetailData;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by lu on 15-6-17.
 */
public class CircleProgressViewFactory {

    public static class DownloadCircleProgressView extends CircleProgressView {
        private DownloadTask task = null;
        private VIEW_STATE state = null;
        private String pkgName = null;
        private String tag = null;
        private Context mContext = null;

        public DownloadCircleProgressView(Context context) {
            this(context, null);
        }

        public DownloadCircleProgressView(Context context, DownloadTask task) {
            super(context);
            mContext = context;
            bindTask(task);
        }

        public void setTAG(String tag) {
            this.tag = tag;
        }

        public String getTAG() {
            return tag;
        }

        public void setPkgName(String pkgName) {
            this.pkgName = pkgName;
        }

        public String getPkgName() {
            return pkgName;
        }

        public void bindTask(DownloadTask task) {
            this.task = task;
        }

        public void setViewState(VIEW_STATE state) {
            this.state = state;
        }

        public VIEW_STATE getViewState() {
            return state;
        }

        public void fakeDownloading() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        setState(PROGRESS_STATE.WAITING);
                        Thread.sleep(500);
                        setState(PROGRESS_STATE.DOWNLOADING);
                        int count = 0;
                        while (count++ < 100) {
                            setProgress(count);
                            Thread.sleep(10);
                        }
                        setState(PROGRESS_STATE.INSTALLING);
                        if (Android.isPackageInstalled(mContext, pkgName)) {
                            Thread.sleep(1000);
                            synchronized (listeners) {
                                for (final CircleProgressViewFactoryListener l : listeners) {
                                    CoocaaApplication.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                l.onRemoved(DownloadCircleProgressView.this);
                                            } catch (Exception e) {
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        public DownloadTask getBindTask() {
            return task;
        }
    }

    private static class DownloadTaskExtra extends JObject {
        public static final String HALL_TASK_FLAG = "HALL_TASK_FLAG";
        public static final String HALL_TASK_FLAG_DOWNLOAD = HALL_TASK_FLAG + "_DOWNLOAD";
        public static final String HALL_TASK_FLAG_UPGRADE = HALL_TASK_FLAG + "_UPGRADE";

        public String flag, pkgName;

        public DownloadTaskExtra() {

        }

        public DownloadTaskExtra(String flag, String pkgName) {
            this.flag = flag;
            this.pkgName = pkgName;
        }
    }

    public static interface CircleProgressViewFactoryListener {
        void onRemoved(CircleProgressView view);
    }

    private static List<CircleProgressViewFactoryListener> listeners = new ArrayList<CircleProgressViewFactoryListener>();

    public static void addListener(CircleProgressViewFactoryListener l) {
        synchronized (listeners) {
            if (!listeners.contains(l)) listeners.add(l);
        }
    }

    public static void removeListener(CircleProgressViewFactoryListener l) {
        synchronized (listeners) {
            listeners.remove(l);
        }
    }


    //分两级
    //第一级：key:pkgName  value:<Tag,view[]>
    //第二级：key:tag   value:view[]
//    private static Cache<String, Cache<String, DownloadCircleProgressView[]>> viewCache = new Cache<String, Cache<String, DownloadCircleProgressView[]>>();


    private static Cache<String, Runnable> upgradeCheckerRunnables = new Cache<String, Runnable>();
    private static Cache<String, DownloadTask> installTaskCache = new Cache<String, DownloadTask>();
    private static Cache<String, String> upgrade_install_packages = new Cache<String, String>();

    private static ILiteDownloaderService downloader = null;

    //tag：每一页给一个唯一的tag，
//    public static synchronized DownloadCircleProgressView[] create(Context context, String pkgName, String tag, boolean isInstalled, int count, boolean bInit) {
//        if (downloader == null) {
//            LogUtils.i("", "cirView downloader:" + "; " + isInstalled);
//            IBinder binder = XServiceManager.getService("com.coocaa.x.service.litedownloader2");
//            downloader = ILiteDownloaderService.Stub.asInterface(binder);
//            LogUtils.i("", "cirView downloader:" + "; " + isInstalled);
//            try {
//                downloader.addListener(listener);
//                XServiceManager.getLitePMService().addInstallListener(installListener);
//            } catch (RemoteException e) {
//            }
//        }
//
//        //如果是初始化，则寻找pkgName对应的下载任务，如果对应的下载任务存在且没有完成，则创建view
//        boolean hasDownload = false;
//        DownloadCircleProgressView[] ret = null;
//        if (bInit) {
//            try {
//                List<DownloadTask> taskList = downloader.getList();
//                LogUtils.i("factory", "taskList.size: " + taskList.size());
//                if (taskList != null && taskList.size() > 0) {
//                    for (DownloadTask _task : taskList) {
//                        if (_task.flag.equals(HALL_TASK_FLAG_DOWNLOAD)) {
//                            if (_task.extra.equals(pkgName)) {
//                                int status = downloader.getStatus(_task);
//                                LogUtils.i("factory", "taskstatus: " + status);
//                                if (status == DownloadTask.STATUS_WAITING
//                                        || status == DownloadTask.STATUS_PAUSE
//                                        || status == DownloadTask.STATUS_DOWNLOADING
//                                        || status == -ErrorCode.EC_LITEDOWNLOADER_TASK_NOT_START) {
//                                    hasDownload = true;
//                                    break;
//                                } else {
//                                    downloader.cancel(_task);
//                                }
//                                return null;
//                            }
//                        }
//
//                    }
//                }
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
//
//            if (hasDownload) {
//                LogUtils.i("factory", "hasDownload: " + hasDownload + "isInstalled: " + isInstalled);
//                if (isInstalled) {
//                    ret = checkUpgrade(context, pkgName, tag, count);
//                } else {
//                    ret = performDownload(context, pkgName, tag, count);
//                }
//            }
//
//            return ret;
//        }
//
//
//        if (isInstalled) {
//            ret = checkUpgrade(context, pkgName, tag, count);
//        } else {
//            ret = performDownload(context, pkgName, tag, count);
//        }
//        return ret;
//    }
//
//    public static synchronized DownloadCircleProgressView create(Context context, String pkgName, String tag, boolean isInstalled, boolean bInit) {
//        return create(context, pkgName, tag, isInstalled, 1, bInit)[0];
//    }

    private static String getDownurl(String appid, String usercount) {
        try {
            String downurl = CoocaaApplication.getCoocaaWebService().getAppStoreService().getDownAddress(
                    Integer.valueOf(appid), usercount);
            System.out.println("download url:" + downurl);
            return downurl;
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("获取应用下载地址接口",
                    Android.throwable2String(e));
            System.out.println("错误原因：" + e.getErrormsg());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

//    private static DownloadCircleProgressView[] checkUpgrade(Context context, final String pkgName, final String tag, int count) {
//        if (!upgradeCheckerRunnables.containsKey(pkgName)) {
//            {
//                //todo 1.1、获取downloader中的下载任务列表，筛选出flag为HALL_TASK_FLAG_UPGRADE的任务列表
//                try {
//                    List<DownloadTask> taskList = downloader.getList();
//                    if (taskList != null && taskList.size() > 0) {
//                        for (DownloadTask task : taskList) {
//                            DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(task.extra, DownloadTaskExtra.class);
//                            if (extra != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_UPGRADE)) {
//                                if (task.extra.equals(pkgName)) {
//                                    int status = downloader.getStatus(task);
//                                    if (status == DownloadTask.STATUS_SUCCESS) {
//                                        Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(pkgName);
//                                        if (tagViews == null) {
//                                            tagViews = new Cache<String, DownloadCircleProgressView[]>();
//                                            viewCache.add(pkgName, tagViews);
//                                        }
//                                        DownloadCircleProgressView[] views = tagViews.get(tag);
//                                        if (views == null) {
//                                            views = new DownloadCircleProgressView[count];
//                                            for (int i = 0; i < count; i++) {
//                                                views[i] = new DownloadCircleProgressView(context, task);
//                                            }
//                                            tagViews.add(tag, views);
//                                        }
//                                        String path = task.save_path;
//                                        XServiceManager.getLitePMService().install(path, true);
//                                        return views;
//                                    }
//                                    return null;
//                                }
//                            }
//
//                        }
//                    }
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
//                //todo 1.2、从1.1筛选出的任务列表中，查找状态为已完成的任务，并且extra.equle(pkgName)==true
//
//                //todo 1.3、如果1.2中有复合条件的task，则创建DownloadCircleProgressView并绑定此task，设置view的状态为"正在更新"
//                //todo 1.4、获取task的存储路径，并调用PMService的静默安装接口进行安装，监听安装回调
//                //todo 1.5、返回创建的view
//            }
//
//            {
//                //todo 2.0、如果1.0中没有执行安装的动作，则执行此代码段
//                Runnable runnable = new Runnable() {
//                    @Override
//                    public void run() {
//                        //todo 2.1、通过contentservice获取pkgname应用的更新信息
//                        //todo 2.2、如果有可用更新，则获取下载url
//                        //todo 2.3、通过downloader获取存储路径，并创建downloadtask，设置downloadtask的flag为HALL_TASK_FLAG_UPGRADE,extra为pkgName
//                        //todo 2.4、start downloadtask
//
//                        List<AppUpdateBean> appdatas = null;
//                        LiteURI uri = LiteURI.create("apps://com.coocaa.app/update_apps");
//                        uri.addParams("pkg", pkgName);
//                        String json = null;
//                        try {
//                            json = LiteContentServiceConnecter.getService().call(uri.toString());
//                        } catch (RemoteException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//                        if (json != null) {
//                            RP_Update_Apps rp = RP_Installed_Apps.parseJObject(json, RP_Update_Apps.class);
//                            appdatas = rp.resource.resource_items;
//                        }
//
//                        if (appdatas != null && appdatas.size() > 0) {
//                            AppUpdateBean updateBean = null;
//                            for (AppUpdateBean bean : appdatas) {
//                                if (bean.bean.packagename.equals(pkgName)) {
//                                    updateBean = bean;
//                                    break;
//                                }
//                            }
//
//                            if (updateBean != null && updateBean.bean != null) {
//                                int id = updateBean.bean.appid;
//                                String downloadUrl = getDownurl(String.valueOf(id), "");
//                                try {
//                                    String savePath = downloader.getSavePath() + "/" + pkgName + ".apk";
//                                    DownloadTask task = new DownloadTask(savePath, downloadUrl);
//                                    task.flag = HALL_TASK_FLAG_UPGRADE;
//                                    task.extra = pkgName;
//                                    downloader.start(task);
//
//                                    upgrade_install_packages.add(pkgName, HALL_TASK_FLAG_UPGRADE);
//                                } catch (RemoteException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//
//                        }
//                        upgradeCheckerRunnables.remove(pkgName);
//                    }
//                };
//                upgradeCheckerRunnables.add(pkgName, runnable);
//                CoocaaApplication.post(runnable);
//                return null;
//            }
//        }
//        return null;
//    }
//
//    private static DownloadCircleProgressView[] performDownload(Context context, final String pkgName, final String tag, int count) {
//        Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(pkgName);
//        if (tagViews == null) {
//            tagViews = new Cache<String, DownloadCircleProgressView[]>();
//            viewCache.add(pkgName, tagViews);
//        }
//
//        DownloadCircleProgressView[] views = tagViews.get(tag);
//        if (views == null) {
//            LogUtils.i("factory", "views == null");
//            views = new DownloadCircleProgressView[count];
//            tagViews.add(tag, views);
//
//            DownloadTask task = null;
//            //看下载任务是否有该应用
//            try {
//                List<DownloadTask> taskList = downloader.getList();
//                if (taskList != null && taskList.size() > 0) {
//                    for (DownloadTask _task : taskList) {
//                        if (_task.flag.equals(HALL_TASK_FLAG_DOWNLOAD)) {
//                            if (_task.extra.equals(pkgName)) {
//                                int status = downloader.getStatus(_task);
//                                if (status != DownloadTask.STATUS_SUCCESS) {
//                                    task = _task;
//                                    break;
//                                }
//                            }
//                        }
//
//                    }
//                }
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
//
//            //创建调用者需要的circleView
//            for (int i = 0; i < count; i++) {
//                DownloadCircleProgressView view = new DownloadCircleProgressView(context);
//                //todo 1.1、设置view的状态为等待下载
//                view.setState(CircleProgressView.PROGRESS_STATE.WAITING);
//                if (task != null) {
//                    view.bindTask(task);
//                    int status = 0;
//                    try {
//                        status = downloader.getStatus(task);
//                        LogUtils.i("factory", "status : " + status);
//                        if (status == DownloadTask.STATUS_DOWNLOADING) {
//                            view.setState(CircleProgressView.PROGRESS_STATE.DOWNLOADING);
//                        } else if (status == DownloadTask.STATUS_WAITING) {
//                            view.setState(CircleProgressView.PROGRESS_STATE.WAITING);
//                        } else if (status == DownloadTask.STATUS_PAUSE
//                                || status == ErrorCode.EC_LITEDOWNLOADER_TASK_NOT_START) {
//                            downloader.start(task);
//                        } else {
//                            downloader.cancel(task);
//                            downloader.start(task);
//                        }
//
//                        if (upgrade_install_packages.containsKey(pkgName)) {
//                            upgrade_install_packages.remove(pkgName);
//                        }
//
//                        upgrade_install_packages.add(pkgName, HALL_TASK_FLAG_DOWNLOAD);
//                    } catch (RemoteException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                views[i] = view;
//            }
//
//            //如果下载任务里还没改应用，则创建下载任务
//            if (task == null) {
//                final Cache<String, DownloadCircleProgressView[]> _tagViews = tagViews;
//                CoocaaApplication.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        //todo 2.1、通过contentservice获取pkgname应用的下载url
//                        //todo 2.2、通过downloader获取存储路径，并创建downloadtask，设置downloadtask的flag为HALL_TASK_FLAG_DOWNLOAD,extra为pkgName
//                        //todo 2.3、通过viewCache获取pkgName对应的DownloadCircleProgressView，并将downloadtask与之绑定
//                        //todo 2.4、start downloadtask
//                        String save_path = null;
//                        try {
//                            save_path = downloader.getSavePath() + "/" + pkgName + ".apk";
//                        } catch (RemoteException e) {
//                            e.printStackTrace();
//                        }
//                        String url = null;
//                        try {
//                            List<AppDetailData> list = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppDetail(new String[]{pkgName});
//                            LogUtils.d("factory", "CPVF getAppDetail by pkgname:" + pkgName + "   result:" + list);
//                            if (list != null && list.size() == 1) {
//                                AppDetailData data = list.get(0);
//                                LogUtils.d("factory", "CPVF getAppDetail by pkgname:" + pkgName + "   id:" + data.id);
//                                url = getDownurl(data.id, "");
//                                LogUtils.d("factory", "CPVF getDownurl by pkgname:" + pkgName + "   url:" + url);
//                            }
//                        } catch (AppStoreException e) {
//                            e.printStackTrace();
//                        }
//                        if (url != null) {
//                            DownloadTask task = new DownloadTask(save_path, url);//"http://apkupdate.miui.com/miuilite/MiuiLite_2.6.0_1000.apk");
//                            task.flag = HALL_TASK_FLAG_DOWNLOAD;
//                            task.extra = pkgName;
//                            task.action = DownloadTask.DownloadTaskOnSuccessAction.createAutoInstallAction(task.save_path);
//                            DownloadCircleProgressView[] _views = _tagViews.get(tag);
//                            if (_views != null) {
//                                for (DownloadCircleProgressView _view : _views) {
//                                    _view.bindTask(task);
//                                    LogUtils.d("factory", "bindTask");
//                                }
//                            }
//                            try {
//                                int ret = downloader.start(task);
//                                if (ret != ErrorCode.EC_SUCCESS) {
//                                    downloader.cancel(task);
//                                    downloader.start(task);
//                                }
//                                LogUtils.d("factory", "task ret: " + ret);
//                                LogUtils.d("factory", "task size: " + downloader.getList().size());
//                            } catch (RemoteException e) {
//                                e.printStackTrace();
//                            }
//                            upgrade_install_packages.add(pkgName, HALL_TASK_FLAG_DOWNLOAD);
//                        } else {
//                            synchronized (listeners) {
//                                DownloadCircleProgressView[] _views = _tagViews.get(pkgName);
//                                viewCache.remove(pkgName);
//                                if (_views != null) {
//                                    for (DownloadCircleProgressView _view : _views) {
//                                        for (CircleProgressViewFactoryListener l : listeners)
//                                            l.onRemoved(_view);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                });
//            }
//        } else {
//            //todo 3.1、获取view绑定的task的下载状态(如果有绑定上task)
//            //todo 3.2、根据task下载状态初始化view的状态
//            LogUtils.i("factory", "views not null");
//            for (DownloadCircleProgressView view : views) {
//
//                DownloadTask task = view.getBindTask();
//                if (task != null) {
//                    try {
//                        int status = downloader.getStatus(task);
//                        LogUtils.i("factory", "status: " + status);
//                        switch (status) {
//                            case DownloadTask.STATUS_WAITING:
//                                view.setState(CircleProgressView.PROGRESS_STATE.WAITING);
//                                break;
//                            case -ErrorCode.EC_LITEDOWNLOADER_TASK_NOT_START:
//                                view.setState(CircleProgressView.PROGRESS_STATE.WAITING);
//                                downloader.start(task);
//                                break;
//                            case DownloadTask.STATUS_PAUSE:
//                                downloader.start(task);
//                                break;
//                            case DownloadTask.STATUS_DOWNLOADING:
//                                view.setState(CircleProgressView.PROGRESS_STATE.DOWNLOADING);
//                                break;
//                            default:
//                                downloader.cancel(task);
//                                downloader.start(task);
//                                break;
//                        }
//                    } catch (RemoteException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//            }
//        }
//        return views;
//    }

    private static ILiteDownloadServiceListener.Stub listener = new ILiteDownloadServiceListener.Stub() {
        @Override
        public void onStarted(DownloadTask task) throws RemoteException {
            DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(task.extra, DownloadTaskExtra.class);
            if (extra != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD)) {
                LogUtils.i("factory", "onStarted " + extra.pkgName);
                Map<String, DownloadCircleProgressView> map = null;
                synchronized (viewMap) {
                    map = viewMap.get(extra.pkgName);
                }
                if (map == null)
                    return;
                synchronized (map) {
                    Set<String> keys = map.keySet();
                    for (String key : keys) {
                        DownloadCircleProgressView view = map.get(key);
                        view.setState(CircleProgressView.PROGRESS_STATE.DOWNLOADING);
                        view.setProgress(0);
                    }
                }
//                Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(task.extra);
//                if (tagViews != null) {
//
//                    List<DownloadCircleProgressView[]> listViews = tagViews.values();
//
//                    for (DownloadCircleProgressView[] views : listViews)
//                        if (views != null) {
//
//                            for (DownloadCircleProgressView view : views) {
//                                if (view == null) {
//                                    LogUtils.i("factory", "view == null");
//                                    continue;
//                                }
//                                view.setState(CircleProgressView.PROGRESS_STATE.DOWNLOADING);
//                                view.setProgress(0);
//                            }
//                        }
//                }
            }
        }

        @Override
        public void onPaused(DownloadTask task) throws RemoteException {
//            if (task.flag.equals(HALL_TASK_FLAG_DOWNLOAD))
//                ;
        }

        @Override
        public void onCanceled(DownloadTask task) throws RemoteException {
//            if (task.flag.equals(HALL_TASK_FLAG_DOWNLOAD))
//                ;
        }

        @Override
        public void onProgressUpdate(DownloadTask task, int percent, long fileSize, long downloadedSize) throws RemoteException {
            DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(task.extra, DownloadTaskExtra.class);
            if (extra != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD)) {
                Map<String, DownloadCircleProgressView> map = null;
                synchronized (viewMap) {
                    map = viewMap.get(extra.pkgName);
                }
                if (map == null)
                    return;
                synchronized (map) {
                    Set<String> keys = map.keySet();
                    for (String key : keys) {
                        DownloadCircleProgressView view = map.get(key);
                        view.setProgress(percent);
                    }
                }


//                Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(task.extra);
//                if (tagViews != null) {
//                    List<DownloadCircleProgressView[]> listViews = tagViews.values();
//                    for (DownloadCircleProgressView[] views : listViews) {
//                        if (views != null) {
//                            for (DownloadCircleProgressView view : views) {
//                                if (view != null)
//                                    view.setProgress(percent);
//                            }
//                        }
//                    }
//                }
            }
        }

        @Override
        public void onSuccess(DownloadTask task) throws RemoteException {
            DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(task.extra, DownloadTaskExtra.class);
            if (extra != null) {
                if (extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD) || extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_UPGRADE)) {
                    installTaskCache.add(task.extra, task);
                }
            }
        }

        @Override
        public void onError(DownloadTask task, int err_code, String err_msg) throws RemoteException {
            DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(task.extra, DownloadTaskExtra.class);
            if (extra != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD)) {
                Map<String, DownloadCircleProgressView> map = null;
                synchronized (viewMap) {
                    map = viewMap.get(extra.pkgName);
                }
                if (map == null)
                    return;
                synchronized (map) {
                    Set<String> keys = map.keySet();
                    for (String key : keys) {
                        final DownloadCircleProgressView view = map.get(key);
//                        deleteSavedState(extra.pkgName, view.getTAG());
                        synchronized (listeners) {
                            for (final CircleProgressViewFactoryListener l : listeners) {
                                CoocaaApplication.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            l.onRemoved(view);
                                        } catch (Exception e) {
                                        }
                                    }
                                });
                            }
                        }
                    }
                }
//                Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(task.extra);
//                viewCache.remove(task.extra);
//                if (tagViews != null) {
//                    List<DownloadCircleProgressView[]> listViews = tagViews.values();
//                    for (DownloadCircleProgressView[] views : listViews) {
//                        if (views != null) {
//                            for (final DownloadCircleProgressView view : views) {
//                                synchronized (listeners) {
//                                    for (final CircleProgressViewFactoryListener l : listeners) {
//                                        CoocaaApplication.post(new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                try {
//                                                    l.onRemoved(view);
//                                                } catch (Exception e) {
//                                                }
//                                            }
//                                        });
//                                    }
//                                }
//                            }
//                        }
//                    }
//                    tagViews.clear();
//                    viewCache.remove(task.extra);
//                }
            } else if (extra != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_UPGRADE))
                ;
        }
    };

    private static ILitePMInstallListener.Stub installListener = new ILitePMInstallListener.Stub() {
        @Override
        public void onInstallStart(String apkfile, AppInfo pkgname, final InstallParams params) throws RemoteException {
            LogUtils.d("factory", "onInstallStart pkgName:" + pkgname.pkgName);
            if (pkgname != null) {
                String flag = upgrade_install_packages.get(pkgname.pkgName);
                upgrade_install_packages.remove(pkgname.pkgName);

                LogUtils.d("factory", "flag = " + flag);
                if (flag != null) {
                    if (flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD)) {
                        Map<String, DownloadCircleProgressView> map = null;
                        synchronized (viewMap) {
                            map = viewMap.get(pkgname.pkgName);
                        }
                        if (map == null)
                            return;
                        Map<String, String> _savedStateMap = savedStateMap.get(pkgname.pkgName);
                        if (_savedStateMap != null) {
                            synchronized (_savedStateMap) {
                                Set<String> keys = _savedStateMap.keySet();
                                for (String key : keys) {
                                    _savedStateMap.put(key, VIEW_STATE.INSTALLING.toString());
                                }
                            }
                        }

                        synchronized (map) {
                            Set<String> keys = map.keySet();
                            for (String key : keys) {
                                DownloadCircleProgressView view = map.get(key);
                                view.setState(CircleProgressView.PROGRESS_STATE.INSTALLING);
                            }
                        }

//                        Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(pkgname.pkgName);
//                        if (tagViews != null) {
//                            List<DownloadCircleProgressView[]> listViews = tagViews.values();
//                            for (DownloadCircleProgressView[] views : listViews) {
//                                if (views != null) {
//                                    LogUtils.d("factory", "onInstallStart CircleProgressView.PROGRESS_STATE.INSTALLING!!");
//                                    for (DownloadCircleProgressView view : views)
//                                        if (view != null)
//                                            view.setState(CircleProgressView.PROGRESS_STATE.INSTALLING);
//                                }
//                            }
//                        }
                    } else if (flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_UPGRADE)) {
                        Map<String, DownloadCircleProgressView> map = null;
                        synchronized (viewMap) {
                            map = viewMap.get(pkgname.pkgName);
                        }
                        if (map == null)
                            return;
                        Map<String, String> _savedStateMap = savedStateMap.get(pkgname.pkgName);
                        if (_savedStateMap != null) {
                            synchronized (_savedStateMap) {
                                Set<String> keys = _savedStateMap.keySet();
                                for (String key : keys) {
                                    _savedStateMap.put(key, VIEW_STATE.UPGRADING.toString());
                                }
                            }
                        }
                        synchronized (map) {
                            Set<String> keys = map.keySet();
                            for (String key : keys) {
                                DownloadCircleProgressView view = map.get(key);
                                view.setState(CircleProgressView.PROGRESS_STATE.UPGRADING);
                            }
                        }
//                        
//                        
//                        Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(pkgname.pkgName);
//                        if (tagViews != null) {
//                            List<DownloadCircleProgressView[]> listViews = tagViews.values();
//                            for (DownloadCircleProgressView[] views : listViews) {
//                                if (views != null) {
//                                    LogUtils.d("factory", "onInstallStart CircleProgressView.PROGRESS_STATE.UPGRADING!!");
//                                    for (DownloadCircleProgressView view : views)
//                                        if (view != null)
//                                            view.setState(CircleProgressView.PROGRESS_STATE.UPGRADING);
//                                }
//                            }
//                        }
                    }
                }
            }
        }

        @Override
        public void onInstallEnd(String apkfile, AppInfo pkgname, int result, String extra, final InstallParams params) throws RemoteException {
            LogUtils.d("factory", "onInstallEnd pkgName:" + pkgname.pkgName + "  result:" + result);

            if (pkgname != null) {
                Map<String, DownloadCircleProgressView> map = null;
                synchronized (viewMap) {
                    map = viewMap.get(pkgname.pkgName);
                }
                if (map == null)
                    return;
                synchronized (map) {
                    Set<String> keys = map.keySet();
                    for (String key : keys) {
                        final DownloadCircleProgressView view = map.get(key);
                        deleteSavedState(pkgname.pkgName, view.getTAG());
                        final DownloadTask task = view.getBindTask();
                        if (task != null) {
                            CoocaaApplication.post(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        LogUtils.d("factory", "downloader.cancel");
                                        downloader.cancel(task);
                                    } catch (RemoteException e) {
                                    }
                                }
                            });
                        } else {
                            LogUtils.d("factory", "task null");
                        }

                        synchronized (listeners) {
                            for (final CircleProgressViewFactoryListener l : listeners) {
                                CoocaaApplication.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            l.onRemoved(view);
                                        } catch (Exception e) {
                                        }
                                    }
                                });
                            }
                        }
                    }
                    map.clear();
                }
                synchronized (viewMap) {
                    viewMap.remove(pkgname.pkgName);
                }

//                Cache<String, DownloadCircleProgressView[]> tagViews = viewCache.get(pkgname.pkgName);
//                if (tagViews != null) {
//                    List<DownloadCircleProgressView[]> listViews = tagViews.values();
//                    for (DownloadCircleProgressView[] views : listViews) {
//                        if (views != null) {
//                            LogUtils.d("factory", "onInstallEnd removed!!");
//                            for (final DownloadCircleProgressView view : views) {
//                                final DownloadTask task = view.getBindTask();
//                                if (task != null) {
//                                    CoocaaApplication.post(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            try {
//                                                LogUtils.d("factory", "downloader.cancel");
//                                                downloader.cancel(task);
//                                            } catch (RemoteException e) {
//                                            }
//                                        }
//                                    });
//                                } else {
//                                    LogUtils.d("factory", "task null");
//                                }
//
//                                synchronized (listeners) {
//                                    for (final CircleProgressViewFactoryListener l : listeners) {
//                                        CoocaaApplication.post(new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                try {
//                                                    l.onRemoved(view);
//                                                } catch (Exception e) {
//                                                }
//                                            }
//                                        });
//                                    }
//                                }
//                            }
//                        }
//                    }
//                    tagViews.clear();
//
//                }
//                viewCache.remove(pkgname.pkgName);
            }

            LogUtils.d("factory", "onInstallEnd end");
        }
    };

    private static enum VIEW_STATE {
        DOWNLOADING,
        FAKE_DOWNLOADING,
        INSTALLING,
        UPGRADING,
    }


    private synchronized static void initDownloader() {
        if (downloader == null) {
            try {
                String json = XServiceManager.getLiteConfigService().getStringValue("hall_view_state", "");
                LogUtils.d("json1", "init savedStateMap json:" + json);
                savedStateMap = (Map<String, Map<String, String>>) JSONObject.parse(json);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            if (savedStateMap == null)
                savedStateMap = new HashMap<String, Map<String, String>>();
            IBinder binder = XServiceManager.getService("com.coocaa.x.service.litedownloader2");
            downloader = ILiteDownloaderService.Stub.asInterface(binder);
            try {
                downloader.addListener(listener);
                XServiceManager.getLitePMService().addInstallListener(installListener);
            } catch (RemoteException e) {
            }
        }
    }

    private static Map<String, Map<String, String>> savedStateMap = null;

    private synchronized static VIEW_STATE getSavedState(String pkgName, String tag) {
        synchronized (savedStateMap) {
            Map<String, String> _savedStateMap = savedStateMap.get(pkgName);
            if (_savedStateMap != null) {
                synchronized (_savedStateMap) {
                    try {
                        return VIEW_STATE.valueOf(_savedStateMap.get(tag));
                    } catch (Exception e) {
                    }
                }
            }
        }
        return null;
    }

    private synchronized static void updateSavedState(String pkgName, String tag, VIEW_STATE state) {
        synchronized (savedStateMap) {
            Map<String, String> _savedStateMap = savedStateMap.get(pkgName);
            if (_savedStateMap == null) {
                _savedStateMap = new HashMap<String, String>();
                savedStateMap.put(pkgName, _savedStateMap);
            }
            synchronized (_savedStateMap) {
                _savedStateMap.put(tag, state.toString());
            }
            String json = JSONObject.toJSONString(savedStateMap);
            LogUtils.d("json1", "updateSavedState savedStateMap json:" + json);
            try {
                XServiceManager.getLiteConfigService().saveStringConfig("hall_view_state", json);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized static void deleteSavedState(String pkgName, String tag) {
        synchronized (savedStateMap) {
            Map<String, String> _savedStateMap = savedStateMap.get(pkgName);
            if (_savedStateMap != null) {
                synchronized (_savedStateMap) {
                    _savedStateMap.remove(tag);
                }
                savedStateMap.put(pkgName, _savedStateMap);
                String json = JSONObject.toJSONString(savedStateMap);
                LogUtils.d("json1", "deleteSavedState savedStateMap json:" + json);
                try {
                    XServiceManager.getLiteConfigService().saveStringConfig("hall_view_state", json);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private synchronized static VIEW_STATE getCurrentState(String pkgName, String tag) {
        if (isDownloading(pkgName))
            return VIEW_STATE.DOWNLOADING;
        if (isInstalling(pkgName))
            return VIEW_STATE.INSTALLING;
        return null;
    }

    private synchronized static VIEW_STATE getCurrentTrueState(String pkgName, String tag) {
        return null;
    }

    private static Map<String, Map<String, DownloadCircleProgressView>> viewMap = new HashMap<String, Map<String, DownloadCircleProgressView>>();


    private synchronized static DownloadCircleProgressView createView(Context context, String pkgName, String tag, VIEW_STATE state) {
        synchronized (viewMap) {
            Map<String, DownloadCircleProgressView> map = viewMap.get(pkgName);
            if (map == null) {
                map = new HashMap<String, DownloadCircleProgressView>();
                viewMap.put(pkgName, map);
            }
            synchronized (map) {
                if (map.containsKey(tag))
                    return map.get(tag);
                DownloadCircleProgressView view = new DownloadCircleProgressView(context);
                view.setTAG(tag);
                view.setPkgName(pkgName);
                view.setViewState(state);

                switch (state) {
                    case DOWNLOADING: {
                        DownloadTask task = null;
                        //看下载任务是否有该应用
                        try {
                            List<DownloadTask> taskList = downloader.getList();
                            if (taskList != null && taskList.size() > 0) {
                                for (DownloadTask _task : taskList) {
                                    DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(_task.extra, DownloadTaskExtra.class);
                                    if (extra != null && extra.flag != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD)) {
                                        if (extra.pkgName != null && extra.pkgName.equals(pkgName)) {
                                            int status = downloader.getStatus(_task);
                                            if (status != DownloadTask.STATUS_SUCCESS) {
                                                task = _task;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }

                        //todo 1.1、设置view的状态为等待下载
                        view.setState(CircleProgressView.PROGRESS_STATE.WAITING);
                        if (task != null) {
                            view.bindTask(task);
                            int status = 0;
                            try {
                                status = downloader.getStatus(task);
                                LogUtils.i("factory", "status : " + status);
                                if (status == DownloadTask.STATUS_DOWNLOADING) {
                                    view.setState(CircleProgressView.PROGRESS_STATE.DOWNLOADING);
                                } else if (status == DownloadTask.STATUS_WAITING) {
                                    view.setState(CircleProgressView.PROGRESS_STATE.WAITING);
                                } else if (status == DownloadTask.STATUS_PAUSE
                                        || status == ErrorCode.EC_LITEDOWNLOADER_TASK_NOT_START) {
                                    downloader.start(task);
                                } else if (status == DownloadTask.STATUS_SUCCESS) {
                                    //do nothing
                                } else {
                                    downloader.cancel(task);
                                    downloader.start(task);
                                }
                                if (upgrade_install_packages.containsKey(pkgName)) {
                                    upgrade_install_packages.remove(pkgName);
                                }
                                upgrade_install_packages.add(pkgName, DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    }
                    case FAKE_DOWNLOADING: {
                        view.fakeDownloading();
                        break;
                    }
                    case INSTALLING: {
                        view.setState(CircleProgressView.PROGRESS_STATE.INSTALLING);
                        break;
                    }
                    case UPGRADING: {
                        view.setState(CircleProgressView.PROGRESS_STATE.UPGRADING);
                        break;
                    }
                    default:
                        break;
                }
                map.put(tag, view);
                return view;
            }
        }
    }

    public synchronized static DownloadCircleProgressView create(Context context, String pkgName, String tag, boolean isInstalled, boolean bInit) {
        initDownloader();
        if (bInit) {
            VIEW_STATE saved_state = getSavedState(pkgName, tag);
            if (saved_state != null) {
                VIEW_STATE current_state = getCurrentState(pkgName, tag);
                if (current_state == null) {
                    deleteSavedState(pkgName, tag);
                    return null;
                }
                VIEW_STATE current_true_state = getCurrentTrueState(pkgName, tag);
                if (current_true_state == null) {
                    updateSavedState(pkgName, tag, current_state);
                    return createView(context, pkgName, tag, current_state);
                } else {
                    updateSavedState(pkgName, tag, saved_state);
                    return createView(context, pkgName, tag, saved_state);
                }
            } else
                return null;
        } else {
            if (!isInstalled) {
                VIEW_STATE current_true_state = getCurrentTrueState(pkgName, tag);
                if (current_true_state == null) {
                    VIEW_STATE current_state = getCurrentState(pkgName, tag);
                    if (current_state == null) {
                        if (!Android.isPackageInstalled(context, pkgName)) {
                            DownloadCircleProgressView view = createView(context, pkgName, tag, VIEW_STATE.DOWNLOADING);
                            updateSavedState(pkgName, tag, VIEW_STATE.DOWNLOADING);
                            //do download
                            doDownload(pkgName, view);
                            return view;
                        }
                        return null;
                    } else {
                        switch (current_state) {
                            case DOWNLOADING:
                                updateSavedState(pkgName, tag, VIEW_STATE.DOWNLOADING);
                                return createView(context, pkgName, tag, VIEW_STATE.DOWNLOADING);
                            case INSTALLING:
                                updateSavedState(pkgName, tag, VIEW_STATE.FAKE_DOWNLOADING);
                                return createView(context, pkgName, tag, VIEW_STATE.FAKE_DOWNLOADING);
                            default:
                                return null;
                        }
                    }
                } else {
                    switch (current_true_state) {
                        case DOWNLOADING:
                            updateSavedState(pkgName, tag, VIEW_STATE.DOWNLOADING);
                            return createView(context, pkgName, tag, VIEW_STATE.DOWNLOADING);
                        case INSTALLING:
                            updateSavedState(pkgName, tag, VIEW_STATE.FAKE_DOWNLOADING);
                            return createView(context, pkgName, tag, VIEW_STATE.FAKE_DOWNLOADING);
                        default:
                            return null;
                    }
                }
            } else {
                DownloadTask task = doUpgrade(pkgName);
                if (task != null) {
                    VIEW_STATE current_state = getCurrentState(pkgName, tag);
                    DownloadCircleProgressView view = createView(context, pkgName, tag, VIEW_STATE.UPGRADING);
                    if (current_state == null) {
                        updateSavedState(pkgName, tag, VIEW_STATE.UPGRADING);
                        view.bindTask(task);
                        try {
                            InstallParams params = new InstallParams();
                            params.setFrom(InstallParams.INSTALL_FROM.COOCAA_MARKET);
                            XServiceManager.getLitePMService().install(task.save_path, true, params);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                    return view;
                }
                return null;
            }
        }
    }

    private static DownloadTask doUpgrade(final String pkgName) {
        if (!upgradeCheckerRunnables.containsKey(pkgName)) {
            DownloadTask task = null;
            //看下载任务是否有该应用
            try {
                List<DownloadTask> taskList = downloader.getList();
                if (taskList != null && taskList.size() > 0) {
                    for (DownloadTask _task : taskList) {
                        DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(_task.extra, DownloadTaskExtra.class);
                        if (extra != null && extra.flag != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_UPGRADE)) {
                            if (extra.pkgName != null && extra.pkgName.equals(pkgName)) {
                                int status = downloader.getStatus(_task);
                                if (status == DownloadTask.STATUS_SUCCESS) {
                                    task = _task;
                                    break;
                                }
                            }
                        }
                    }
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            if (task == null) {
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        //todo 2.1、通过contentservice获取pkgname应用的更新信息
                        //todo 2.2、如果有可用更新，则获取下载url
                        //todo 2.3、通过downloader获取存储路径，并创建downloadtask，设置downloadtask的flag为HALL_TASK_FLAG_UPGRADE,extra为pkgName
                        //todo 2.4、start downloadtask

                        List<AppUpdateBean> appdatas = null;
                        LiteURI uri = LiteURI.create("apps://com.coocaa.app/update_apps");
                        uri.addParams("pkg", pkgName);
                        String json = null;
                        try {
                            json = LiteContentServiceConnecter.getService().call(uri.toString());
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        if (json != null) {
                            RP_Update_Apps rp = RP_Installed_Apps.parseJObject(json, RP_Update_Apps.class);
                            appdatas = rp.resource.resource_items;
                        }

                        if (appdatas != null && appdatas.size() > 0) {
                            AppUpdateBean updateBean = null;
                            for (AppUpdateBean bean : appdatas) {
                                if (bean.bean.packagename.equals(pkgName)) {
                                    updateBean = bean;
                                    break;
                                }
                            }

                            if (updateBean != null && updateBean.bean != null) {
                                int id = updateBean.bean.appid;
                                String downloadUrl = getDownurl(String.valueOf(id), "");
                                try {
                                    String savePath = downloader.getSavePath() + "/" + pkgName + ".apk";
                                    DownloadTask task = new DownloadTask(savePath, downloadUrl);
                                    task.extra = new DownloadTaskExtra(DownloadTaskExtra.HALL_TASK_FLAG_UPGRADE, pkgName).toJSONString();
                                    downloader.start(task);
                                    upgrade_install_packages.add(pkgName, DownloadTaskExtra.HALL_TASK_FLAG_UPGRADE);
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }

                        }
                        upgradeCheckerRunnables.remove(pkgName);
                    }
                };
                upgradeCheckerRunnables.add(pkgName, runnable);
                CoocaaApplication.post(runnable);
                return null;
            } else {
                return task;
            }
        }
        return null;
    }

    private static void doDownload(final String pkgName, final DownloadCircleProgressView view) {
        DownloadTask task = null;
        //看下载任务是否有该应用
        try {
            List<DownloadTask> taskList = downloader.getList();
            if (taskList != null && taskList.size() > 0) {
                for (DownloadTask _task : taskList) {
                    DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(_task.extra, DownloadTaskExtra.class);
                    if (extra != null && extra.flag != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD)) {
                        if (extra.pkgName != null && extra.pkgName.equals(pkgName)) {
                            int status = downloader.getStatus(_task);
                            if (status != DownloadTask.STATUS_SUCCESS) {
                                task = _task;
                                break;
                            }
                        }
                    }
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        //如果下载任务里还没改应用，则创建下载任务
        if (task == null) {
            CoocaaApplication.post(new Runnable() {
                @Override
                public void run() {
                    //todo 2.1、通过contentservice获取pkgname应用的下载url
                    //todo 2.2、通过downloader获取存储路径，并创建downloadtask，设置downloadtask的flag为HALL_TASK_FLAG_DOWNLOAD,extra为pkgName
                    //todo 2.3、通过viewCache获取pkgName对应的DownloadCircleProgressView，并将downloadtask与之绑定
                    //todo 2.4、start downloadtask
                    String save_path = null;
                    try {
                        save_path = downloader.getSavePath() + "/" + pkgName + ".apk";
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    String url = null;
                    try {
                        List<AppDetailData> list = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppDetail(new String[]{pkgName});
                        LogUtils.d("factory", "CPVF getAppDetail by pkgname:" + pkgName + "   result:" + list);
                        if (list != null && list.size() == 1) {
                            AppDetailData data = list.get(0);
                            LogUtils.d("factory", "CPVF getAppDetail by pkgname:" + pkgName + "   id:" + data.id);
                            url = getDownurl(data.id, "");
                            LogUtils.d("factory", "CPVF getDownurl by pkgname:" + pkgName + "   url:" + url);
                        }
                    } catch (AppStoreException e) {
                        e.printStackTrace();
                    }
                    if (url != null) {
                        DownloadTask task = new DownloadTask(save_path, url);//"http://apkupdate.miui.com/miuilite/MiuiLite_2.6.0_1000.apk");
                        task.extra = new DownloadTaskExtra(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD, pkgName).toJSONString();
                        task.action = DownloadTask.DownloadTaskOnSuccessAction.createAutoInstallAction(task.save_path);
                        view.bindTask(task);
                        try {
                            int ret = downloader.start(task);
                            if (ret != ErrorCode.EC_SUCCESS) {
                                downloader.cancel(task);
                                downloader.start(task);
                            }
                            LogUtils.d("factory", "task ret: " + ret);
                            LogUtils.d("factory", "task size: " + downloader.getList().size());
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        upgrade_install_packages.add(pkgName, DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD);
                    }
                }
            });
        } else {
            try {
                int status = downloader.getStatus(task);
                LogUtils.i("factory", "status : " + status);
                view.bindTask(task);
                if (status == DownloadTask.STATUS_DOWNLOADING) {
                    view.setState(CircleProgressView.PROGRESS_STATE.DOWNLOADING);
                } else if (status == DownloadTask.STATUS_WAITING) {
                    view.setState(CircleProgressView.PROGRESS_STATE.WAITING);
                } else if (status == DownloadTask.STATUS_PAUSE
                        || status == ErrorCode.EC_LITEDOWNLOADER_TASK_NOT_START) {
                    downloader.start(task);
                } else if (status == DownloadTask.STATUS_SUCCESS) {
                    //do nothing!!
                } else {
                    downloader.cancel(task);
                    downloader.start(task);
                }
                if (upgrade_install_packages.containsKey(pkgName)) {
                    upgrade_install_packages.remove(pkgName);
                }
                upgrade_install_packages.add(pkgName, DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized static boolean isDownloading(String pkg) {
        try {
            List<DownloadTask> taskList = downloader.getList();
            LogUtils.i("factory", "taskList.size: " + taskList.size());
            if (taskList != null && taskList.size() > 0) {
                for (DownloadTask _task : taskList) {
                    DownloadTaskExtra extra = DownloadTaskExtra.parseJObject(_task.extra, DownloadTaskExtra.class);
                    if (extra != null && extra.flag != null && extra.flag.equals(DownloadTaskExtra.HALL_TASK_FLAG_DOWNLOAD)) {
                        if (extra.pkgName != null && extra.pkgName.equals(pkg)) {
                            int status = downloader.getStatus(_task);
                            LogUtils.i("factory", "taskstatus: " + status);
                            if (status == DownloadTask.STATUS_WAITING
                                    || status == DownloadTask.STATUS_PAUSE
                                    || status == DownloadTask.STATUS_DOWNLOADING
                                    || status == -ErrorCode.EC_LITEDOWNLOADER_TASK_NOT_START) {
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private synchronized static boolean isInstalling(String pkg) {
        try {
            int s = XServiceManager.getLitePMService().getAppInstallState(pkg);
            return (s == PMUtils.INSTALL_STATE_INSTALLING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
